package com.tzy.common.utils;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;

import java.util.Calendar;
@Slf4j
public class JsonWebTokenUtil {
    /**
     * 生成token密钥
     * 生成环境配置在配置文件中
     */
    private final static String SECRET = "abc";

    //过期时长
    private final static Integer EXPIRED_HOUR = 240;

    public static String getToken(Integer uid){
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,EXPIRED_HOUR);
        log.info("calendar.getTime()={}",calendar.getTime());
        return JWT.create()
                .withExpiresAt(calendar.getTime())
                .withJWTId(String.valueOf(uid))
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 解析jwt token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            DecodedJWT jwt = jwtVerifier.verify(token);
            return jwt;
        }catch (JWTVerificationException e) {
            return null;
        }
    }

    public static Integer getUserIdFromToken(String token){
        DecodedJWT jwt = verify(token);
        if(jwt==null){
            return 0;
        }
        return Integer.valueOf(jwt.getId());
    }
}
